<?php


	namespace Midi\Translating;

	use Midi\Event;
	use Midi\Event\NoteOnEvent;

	use \Midi\Delta;
	use \Midi\TrackHeader;
	use \Midi\FileHeader;
	use \Midi\Parsing\Parser;
	
	class Printer {
		
		protected $formatter;
		
		protected $parser;
		
		protected $isParsingTrack;
		
		protected $parseTime;
		
		protected $totalTime;
		
		protected $params;
		
		protected $notes;
		protected $tempChannel;
		
		public function __construct(Formatter $formatter, Parser $parser) {
			$this->formatter      = $formatter;
			$this->parser         = $parser;
			$this->isParsingTrack = false;
			$this->parseTime      = 0;
			$this->totalTime      = 0;
			$this->params         = array();
			$this->notes		  = array();
			$this->tempChannel    = -1;
		}
		
		public function  printAllNote() {
			while ($this->printNextNote()) {}
			return $this->notes;
		}
		public function setParameter($key, $value) {
			$this->params[$key] = $value;
		}
		
		public function doPostProcessing(array $params = array()) {
			$processor = $this->formatter->getPostProcessor();
			
			foreach ($params as $key => $value) {
				$processor->setParameter($key, $value);
			}
			
			$processor->execute();
		}
		
		public function printNextNote() {
			$totalTime        = microtime(true);
			$parseTime        = $totalTime;
			$chunk            = $this->parser->parse();
			$this->parseTime += microtime(true) - $parseTime;
			$notEof           = true;
			
			if ($chunk !== null) {
				if ($chunk instanceof Delta) {
					//echo "instanceof Delta";
				} else if ($chunk instanceof Event) {
					if ($chunk instanceof  NoteOnEvent) {
						if ($this->formatter->formatChannel($chunk) != $this->tempChannel) {
							$this->tempChannel = $this->formatter->formatChannel($chunk);
							$this->notes[$this->tempChannel] = array();
							$this->notes[$this->tempChannel][] = $this->formatter->formatEvent($chunk);
						}
						else {
							$this->notes[$this->tempChannel][] = $this->formatter->formatEvent($chunk);
						}
					}
				} else if ($chunk instanceof TrackHeader) {
					//echo "instanceof TrackHeader";
				} else if ($chunk instanceof FileHeader) {
					//echo "instanceof FileHeader";
				}
			} else {
				// not end of file
				$notEof = false;
			}			
			$this->totalTime += microtime(true) - $totalTime;
			
			return $notEof;		
		}
		
		protected function printData($data) {
			echo $data;
		}
		
	}
	
?>